<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  
  <title>跟着Chat学习React之学习Hooks | 添柴阿杰</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="为什么先从Hooks入手？因为之前都是用Vue开发项目，习惯了那些简短好记的生命周期函数，而我在浏览文档时发现React中的生命周期函数都非常难记！此前我也疑惑class组件的写法与函数组件的写法，在明白他们之间的区别后发现了Hooks，这简直是一大福音—当然，在我理解他们的功能之前，只是在记忆这方面来说，这是一大福音。 什么是Hooks？Hooks 是 React 16.8 新引入的一组 API">
<meta property="og:type" content="article">
<meta property="og:title" content="跟着Chat学习React之学习Hooks">
<meta property="og:url" content="https://hajcker_1.gitee.io/hajcker_1.gitee.io/2023/04/09/%E8%B7%9F%E7%9D%80Chat%E5%AD%A6%E4%B9%A0React%E4%B9%8BHooks/index.html">
<meta property="og:site_name" content="添柴阿杰">
<meta property="og:description" content="为什么先从Hooks入手？因为之前都是用Vue开发项目，习惯了那些简短好记的生命周期函数，而我在浏览文档时发现React中的生命周期函数都非常难记！此前我也疑惑class组件的写法与函数组件的写法，在明白他们之间的区别后发现了Hooks，这简直是一大福音—当然，在我理解他们的功能之前，只是在记忆这方面来说，这是一大福音。 什么是Hooks？Hooks 是 React 16.8 新引入的一组 API">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2023-04-09T14:23:52.000Z">
<meta property="article:modified_time" content="2023-04-09T15:09:01.737Z">
<meta property="article:author" content="添柴阿杰">
<meta property="article:tag" content="React">
<meta name="twitter:card" content="summary">
  
    <link rel="alternate" href="/hajcker_1.gitee.io/atom.xml" title="添柴阿杰" type="application/atom+xml">
  
  
    <link rel="shortcut icon" href="/hajcker_1.gitee.io/favicon.png">
  
  
    
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/typeface-source-code-pro@0.0.71/index.min.css">

  
  
<link rel="stylesheet" href="/hajcker_1.gitee.io/css/style.css">

  
    
<link rel="stylesheet" href="/hajcker_1.gitee.io/fancybox/jquery.fancybox.min.css">

  
<meta name="generator" content="Hexo 6.3.0"></head>

<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/hajcker_1.gitee.io/" id="logo">添柴阿杰</a>
      </h1>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/hajcker_1.gitee.io/">Home</a>
        
          <a class="main-nav-link" href="/hajcker_1.gitee.io/archives">Archives</a>
        
      </nav>
      <nav id="sub-nav">
        
          <a id="nav-rss-link" class="nav-icon" href="/hajcker_1.gitee.io/atom.xml" title="RSS 订阅"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="搜索"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" class="search-form-input" placeholder="搜索"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="https://hajcker_1.gitee.io/hajcker_1.gitee.io"></form>
      </div>
    </div>
  </div>
</header>

      <div class="outer">
        <section id="main"><article id="post-跟着Chat学习React之Hooks" class="h-entry article article-type-post" itemprop="blogPost" itemscope itemtype="https://schema.org/BlogPosting">
  <div class="article-meta">
    <a href="/hajcker_1.gitee.io/2023/04/09/%E8%B7%9F%E7%9D%80Chat%E5%AD%A6%E4%B9%A0React%E4%B9%8BHooks/" class="article-date">
  <time class="dt-published" datetime="2023-04-09T14:23:52.000Z" itemprop="datePublished">2023-04-09</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="p-name article-title" itemprop="headline name">
      跟着Chat学习React之学习Hooks
    </h1>
  

      </header>
    
    <div class="e-content article-entry" itemprop="articleBody">
      
        <p>为什么先从Hooks入手？因为之前都是用Vue开发项目，习惯了那些简短好记的生命周期函数，而我在浏览文档时发现React中的生命周期函数都<strong>非常</strong>难记！此前我也疑惑class组件的写法与函数组件的写法，在明白他们之间的区别后发现了Hooks，这简直是一大福音—当然，在我理解他们的功能之前，只是在记忆这方面来说，这是一大福音。</p>
<h2 id="什么是Hooks？"><a href="#什么是Hooks？" class="headerlink" title="什么是Hooks？"></a>什么是Hooks？</h2><p>Hooks 是 React 16.8 新引入的一组 API，可以让您在无需修改组件结构的情况下，在函数组件中使用状态和其他 React 特性（例如生命周期方法、上下文等）。相比之前必须使用 class 组件才能使用这些特性，Hooks 更简单、更灵活，并且可以帮助您减少代码量，提高代码复用率。</p>
<p>通过使用 Hooks，可以将逻辑相关的代码封装到自定义的 Hook 中，并在多个组件间共享这些逻辑代码。例如，如果需要在多个组件中获取和展示某个数据列表，可以将数据请求和处理的逻辑封装到一个自定义的 useDataList Hook 中，然后在需要展现这个数据列表的组件中使用该 Hook 即可。</p>
<p>React 自带了一些常用的钩子，例如 useState、useEffect、useContext、useReducer 等等。</p>
<p>总之，Hooks 是 React 编程中非常重要的一部分，可以大大提高程序员的开发效率，更好地实现组件的逻辑复用。</p>
<h2 id="什么时候用Hooks？"><a href="#什么时候用Hooks？" class="headerlink" title="什么时候用Hooks？"></a>什么时候用Hooks？</h2><p>Hooks 只能在函数组件中使用，并且不能在类组件中使用。这是因为 Hooks 的设计目标是为了解决函数组件中缺乏状态管理和生命周期方法等特性的问题，而类组件已经具有了这些特性，因此不需要使用 Hooks。</p>
<p>在 React 中，函数组件和类组件是两种不同的组件类型，它们具有不同的声明方式、渲染方式和内部实现。类组件是通过继承 React.Component 类来创建的，所以可以使用 class 的语法来声明，而函数组件则是一个简单的 JavaScript 函数。在 React 16.8 之前，函数组件没有状态，也无法处理生命周期方法，因此只能用于展示静态的 UI。但是，随着 Hooks 的出现，函数组件可以像类组件一样拥有自己的状态和生命周期方法，从而成为了类组件的一个有力替代品。</p>
<p>需要注意的是，虽然函数组件被称为无状态组件，但它们仍然可以使用 props 来接收父组件传递的数据，并根据这些数据来渲染 UI。同时，函数组件也可以使用 useContext Hook 来访问上下文数据，并使用 useReducer Hook 实现复杂的状态管理逻辑。因此，在大多数情况下，函数组件已经可以满足我们的需求，而不需要使用类组件。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 函数组件</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">Hello</span>(<span class="params">props</span>) &#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="language-xml"><span class="tag">&lt;<span class="name">div</span>&gt;</span>Hello, &#123;props.name&#125;!<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// class组件</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Hello</span> <span class="keyword">extends</span> <span class="title class_ inherited__">React.Component</span> &#123;</span><br><span class="line">  <span class="title function_">render</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="language-xml"><span class="tag">&lt;<span class="name">div</span>&gt;</span>Hello, &#123;this.props.name&#125;!<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="为什么要有Hooks？"><a href="#为什么要有Hooks？" class="headerlink" title="为什么要有Hooks？"></a>为什么要有Hooks？</h2><h3 id="1、简化状态管理"><a href="#1、简化状态管理" class="headerlink" title="1、简化状态管理"></a>1、简化状态管理</h3><p>在使用类组件时，我们需要定义一个状态对象，并使用 this.setState() 方法来更新它。这样做虽然可以实现状态管理，但这种方式比较繁琐，尤其是当组件状态变得复杂或嵌套时，代码量会非常庞大。而使用 React Hooks 中的 useState，可以让我们在函数组件中轻松管理状态，通过简单的 API 实现状态的读取和更新，使代码更加清晰和易于维护。</p>
<h3 id="2、优化副作用操作"><a href="#2、优化副作用操作" class="headerlink" title="2、优化副作用操作"></a>2、优化副作用操作</h3><p>React 中的副作用操作指的是那些与渲染 UI 无关的操作，例如数据请求、事件监听等。在类组件中，我们通过生命周期方法来处理这些副作用操作，但代码结构不够清晰，而且难以复用。React Hooks 提供了 useEffect 钩子，它可以让我们在函数组件中处理副作用操作，使得代码结构更加清晰明了，同时也提高了代码复用率。</p>
<h3 id="3、提升代码复用率"><a href="#3、提升代码复用率" class="headerlink" title="3、提升代码复用率"></a>3、提升代码复用率</h3><p>在 React 应用程序中，我们通常会编写一些共享逻辑，例如数据请求、表单验证等，以便在多个组件中共享使用。在类组件中，我们可以使用高阶组件、Render Props 等技术来实现代码复用，但这些技术本身比较复杂，不够直观。React Hooks 提供了自定义钩子的机制，可以将我们重复使用的逻辑封装到一个自定义钩子中，然后在多个组件中共享使用，提高了代码复用率和可维护性。</p>
<h2 id="有哪些Hooks？"><a href="#有哪些Hooks？" class="headerlink" title="有哪些Hooks？"></a>有哪些Hooks？</h2><p>我向Chat要了一份代码用例，其中包含了常用的Hooks：useState、useEffect等等，结合代码来理解这些Hooks的作用：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; useState, useEffect, useContext, useReducer, useCallback, useMemo, useRef, useImperativeHandle &#125; <span class="keyword">from</span> <span class="string">&#x27;react&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// useState</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">Counter</span>(<span class="params"></span>) &#123;</span><br><span class="line">  <span class="keyword">const</span> [count, setCount] = <span class="title function_">useState</span>(<span class="number">0</span>);</span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    <span class="language-xml"><span class="tag">&lt;<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">p</span>&gt;</span>You clicked &#123;count&#125; times<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">button</span> <span class="attr">onClick</span>=<span class="string">&#123;()</span> =&gt;</span> setCount(count + 1)&#125;&gt;Click me<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line">  );</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// useEffect</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">DataFetcher</span>(<span class="params"></span>) &#123;</span><br><span class="line">  <span class="keyword">const</span> [data, setData] = <span class="title function_">useState</span>(<span class="literal">null</span>);</span><br><span class="line">  <span class="keyword">const</span> [loading, setLoading] = <span class="title function_">useState</span>(<span class="literal">false</span>);</span><br><span class="line">  <span class="keyword">const</span> [error, setError] = <span class="title function_">useState</span>(<span class="literal">null</span>);</span><br><span class="line"></span><br><span class="line">  <span class="title function_">useEffect</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="title function_">setLoading</span>(<span class="literal">true</span>);</span><br><span class="line">    <span class="title function_">fetch</span>(<span class="string">&#x27;https://jsonplaceholder.typicode.com/todos/1&#x27;</span>)</span><br><span class="line">      .<span class="title function_">then</span>(<span class="function"><span class="params">response</span> =&gt;</span> response.<span class="title function_">json</span>())</span><br><span class="line">      .<span class="title function_">then</span>(<span class="function"><span class="params">jsonData</span> =&gt;</span> &#123;</span><br><span class="line">        <span class="title function_">setData</span>(jsonData);</span><br><span class="line">        <span class="title function_">setLoading</span>(<span class="literal">false</span>);</span><br><span class="line">      &#125;)</span><br><span class="line">      .<span class="title function_">catch</span>(<span class="function"><span class="params">error</span> =&gt;</span> &#123;</span><br><span class="line">        <span class="title function_">setError</span>(error.<span class="property">message</span>);</span><br><span class="line">        <span class="title function_">setLoading</span>(<span class="literal">false</span>);</span><br><span class="line">      &#125;);</span><br><span class="line">  &#125;, []);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span> (loading) <span class="keyword">return</span> <span class="language-xml"><span class="tag">&lt;<span class="name">div</span>&gt;</span>Loading...<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span>;</span><br><span class="line">  <span class="keyword">if</span> (error) <span class="keyword">return</span> <span class="language-xml"><span class="tag">&lt;<span class="name">div</span>&gt;</span>Oops! Something went wrong: &#123;error&#125;<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span>;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> <span class="language-xml"><span class="tag">&lt;<span class="name">div</span>&gt;</span>&#123;JSON.stringify(data)&#125;<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// useContext</span></span><br><span class="line"><span class="keyword">const</span> <span class="title class_">ThemeContext</span> = <span class="title class_">React</span>.<span class="title function_">createContext</span>(<span class="string">&#x27;light&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">ThemeButton</span>(<span class="params"></span>) &#123;</span><br><span class="line">  <span class="keyword">const</span> theme = <span class="title function_">useContext</span>(<span class="title class_">ThemeContext</span>);</span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    <span class="language-xml"><span class="tag">&lt;<span class="name">button</span> <span class="attr">style</span>=<span class="string">&#123;&#123;</span> <span class="attr">backgroundColor:</span> <span class="attr">theme</span> &#125;&#125;&gt;</span>I am styled by theme context!<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span></span><br><span class="line">  );</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// useReducer</span></span><br><span class="line"><span class="keyword">const</span> initialState = &#123; <span class="attr">count</span>: <span class="number">0</span> &#125;;</span><br><span class="line"><span class="keyword">function</span> <span class="title function_">reducer</span>(<span class="params">state, action</span>) &#123;</span><br><span class="line">  <span class="keyword">switch</span> (action.<span class="property">type</span>) &#123;</span><br><span class="line">    <span class="keyword">case</span> <span class="string">&#x27;increment&#x27;</span>:</span><br><span class="line">      <span class="keyword">return</span> &#123; <span class="attr">count</span>: state.<span class="property">count</span> + <span class="number">1</span> &#125;;</span><br><span class="line">    <span class="keyword">case</span> <span class="string">&#x27;decrement&#x27;</span>:</span><br><span class="line">      <span class="keyword">return</span> &#123; <span class="attr">count</span>: state.<span class="property">count</span> - <span class="number">1</span> &#125;;</span><br><span class="line">    <span class="attr">default</span>:</span><br><span class="line">      <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">Error</span>(<span class="string">&#x27;Unsupported action&#x27;</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">CounterWithReducer</span>(<span class="params"></span>) &#123;</span><br><span class="line">  <span class="keyword">const</span> [state, dispatch] = <span class="title function_">useReducer</span>(reducer, initialState);</span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    <span class="language-xml"><span class="tag">&lt;<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">p</span>&gt;</span>Count: &#123;state.count&#125;<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">button</span> <span class="attr">onClick</span>=<span class="string">&#123;()</span> =&gt;</span> dispatch(&#123; type: &#x27;increment&#x27; &#125;)&#125;&gt;+<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">button</span> <span class="attr">onClick</span>=<span class="string">&#123;()</span> =&gt;</span> dispatch(&#123; type: &#x27;decrement&#x27; &#125;)&#125;&gt;-<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line">  );</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// useCallback</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">MemoizedComponent</span>(<span class="params">&#123; name, onClick &#125;</span>) &#123;</span><br><span class="line">  <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">`MemoizedComponent - Rendering for: <span class="subst">$&#123;name&#125;</span>`</span>);</span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    <span class="language-xml"><span class="tag">&lt;<span class="name">button</span> <span class="attr">onClick</span>=<span class="string">&#123;()</span> =&gt;</span> onClick(name)&#125;&gt;</span></span><br><span class="line"><span class="language-xml">      Click Me to Show Name</span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;/<span class="name">button</span>&gt;</span></span></span><br><span class="line">  );</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">ParentComponent</span>(<span class="params"></span>) &#123;</span><br><span class="line">  <span class="keyword">const</span> [name, setName] = <span class="title function_">useState</span>(<span class="string">&#x27;&#x27;</span>);</span><br><span class="line">  <span class="keyword">const</span> handleClick = <span class="title function_">useCallback</span>(<span class="function">(<span class="params">value</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="title function_">setName</span>(value);</span><br><span class="line">  &#125;, []);</span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    <span class="language-xml"><span class="tag">&lt;<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">MemoizedComponent</span> <span class="attr">name</span>=<span class="string">&#x27;Alice&#x27;</span> <span class="attr">onClick</span>=<span class="string">&#123;handleClick&#125;</span> /&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">MemoizedComponent</span> <span class="attr">name</span>=<span class="string">&#x27;Bob&#x27;</span> <span class="attr">onClick</span>=<span class="string">&#123;handleClick&#125;</span> /&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">p</span>&gt;</span>Name: &#123;name&#125;<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line">  );</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// useMemo</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">computeFactorial</span>(<span class="params">n</span>) &#123;</span><br><span class="line">  <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">`Computing factorial(<span class="subst">$&#123;n&#125;</span>)...`</span>);</span><br><span class="line">  <span class="keyword">let</span> result = <span class="number">1</span>;</span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> i = n; i &gt; <span class="number">0</span>; i--) &#123;</span><br><span class="line">    result *= i;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> result;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">FactorialApp</span>(<span class="params">&#123; n &#125;</span>) &#123;</span><br><span class="line">  <span class="keyword">const</span> factorial = <span class="title function_">useMemo</span>(<span class="function">() =&gt;</span> <span class="title function_">computeFactorial</span>(n), [n]);</span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    <span class="language-xml"><span class="tag">&lt;<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">p</span>&gt;</span>Factorial of &#123;n&#125; is: &#123;factorial&#125;<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line">  );</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// useRef</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">InputComponent</span>(<span class="params"></span>) &#123;</span><br><span class="line">  <span class="keyword">const</span> inputRef = <span class="title function_">useRef</span>(<span class="literal">null</span>);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">function</span> <span class="title function_">handleClick</span>(<span class="params"></span>) &#123;</span><br><span class="line">    inputRef.<span class="property">current</span>.<span class="title function_">focus</span>();</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    <span class="language-xml"><span class="tag">&lt;<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&#x27;text&#x27;</span> <span class="attr">ref</span>=<span class="string">&#123;inputRef&#125;</span> /&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">button</span> <span class="attr">onClick</span>=<span class="string">&#123;handleClick&#125;</span>&gt;</span>Focus Input<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line">  );</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// useImperativeHandle</span></span><br><span class="line"><span class="keyword">const</span> <span class="title class_">FancyInput</span> = <span class="title class_">React</span>.<span class="title function_">forwardRef</span>(<span class="function">(<span class="params">props, ref</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">const</span> inputRef = <span class="title function_">useRef</span>(<span class="literal">null</span>);</span><br><span class="line"></span><br><span class="line">  <span class="title function_">useImperativeHandle</span>(ref, <span class="function">() =&gt;</span> (&#123;</span><br><span class="line">    <span class="attr">focus</span>: <span class="function">() =&gt;</span> &#123;</span><br><span class="line">      inputRef.<span class="property">current</span>.<span class="title function_">focus</span>();</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;));</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    <span class="language-xml"><span class="tag">&lt;<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&#x27;text&#x27;</span> <span class="attr">ref</span>=<span class="string">&#123;inputRef&#125;</span> /&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line">  );</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">App</span>(<span class="params"></span>) &#123;</span><br><span class="line">  <span class="keyword">const</span> fancyInputRef = <span class="title function_">useRef</span>(<span class="literal">null</span>);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">function</span> <span class="title function_">handleClick</span>(<span class="params"></span>) &#123;</span><br><span class="line">    fancyInputRef.<span class="property">current</span>.<span class="title function_">focus</span>();</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    <span class="language-xml"><span class="tag">&lt;<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">FancyInput</span> <span class="attr">ref</span>=<span class="string">&#123;fancyInputRef&#125;</span> /&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">button</span> <span class="attr">onClick</span>=<span class="string">&#123;handleClick&#125;</span>&gt;</span>Focus Fancy Input<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line">  );</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="1、useState"><a href="#1、useState" class="headerlink" title="1、useState"></a>1、useState</h3><p>useState 是 React 中最基本的 Hook 之一，它用于在函数组件中使用状态。useState 接受一个初始值，返回一个数组，数组的第一个元素是当前状态的值，第二个元素是一个更新状态的函数。每次调用函数组件时，useState 都会返回原始的状态和更新函数，而不是之前的值。</p>
<h3 id="2、useEffect"><a href="#2、useEffect" class="headerlink" title="2、useEffect"></a>2、useEffect</h3><p>useEffect 是 React 中用于实现生命周期方法的 Hook 之一，它在组件挂载后执行副作用操作，比如获取数据、订阅事件等。useEffect 接受一个回调函数和一个数组，数组中的元素用来控制何时执行回调函数。如果数组为空，则只有在组件挂载后执行一次，如果数组中包含依赖项，则当依赖项发生变化时执行回调函数。</p>
<h3 id="3、useContext"><a href="#3、useContext" class="headerlink" title="3、useContext"></a>3、useContext</h3><p>useContext 是 React 中用来共享数据的 Hook 之一，它可以让我们在组件树中传递数据而不需要一层层地传递 props。useContext 接受一个 context 对象，返回 context 的当前值。如果 context 的值发生变化，使用了 useContext 的组件也会重新渲染。</p>
<h3 id="4、useReducer"><a href="#4、useReducer" class="headerlink" title="4、useReducer"></a>4、useReducer</h3><p>useReducer 是 React 中替代 useState 的 Hook 之一，它更适用于处理复杂的状态逻辑，比如计数器、表单、游戏等。useReducer 接受一个 reducer 函数和一个初始状态，返回一个数组，第一个元素是当前的状态值，第二个元素是一个 dispatch 函数，用于触发更新操作。使用 useReducer 时，我们需要定义一个 reducer 函数来描述每个操作对状态的影响。</p>
<h3 id="5、useCallback"><a href="#5、useCallback" class="headerlink" title="5、useCallback"></a>5、useCallback</h3><p>useCallback 是 React 中优化性能的 Hook 之一，它可以让我们在依赖项没有发生变化时避免重新创建函数。useCallback 接受一个回调函数和一个依赖项数组，返回一个 memoized（被记忆的）回调函数，只有当依赖项发生变化时才会重新创建回调函数。使用 useCallback 可以有效地减少不必要的重新渲染。</p>
<h3 id="6、useMemo"><a href="#6、useMemo" class="headerlink" title="6、useMemo"></a>6、useMemo</h3><p>useMemo 是 React 中优化性能的 Hook 之一，它可以让我们在依赖项没有发生变化时避免重复计算。useMemo 接受一个回调函数和一个依赖项数组，返回一个 memoized（被记忆的）计算结果，只有当依赖项发生变化时才会重新计算结果。使用 useMemo 可以避免在每次渲染组件时都重新计算昂贵的计算结果。</p>
<h3 id="7、useRef"><a href="#7、useRef" class="headerlink" title="7、useRef"></a>7、useRef</h3><p>useRef 是 React 中用于引用 DOM 节点或其他值的 Hook 之一，它可以将一个可变的 ref 绑定到任意一个值上。useRef 返回一个对象，其中 current 属性包含传递给 useRef 的初始值，可以在组件之间共享。与 useState 的区别是，useRef 不会触发组件重新渲染。</p>
<h3 id="8、useImperativeHandle"><a href="#8、useImperativeHandle" class="headerlink" title="8、useImperativeHandle"></a>8、useImperativeHandle</h3><p>useImperativeHandle 是 React 中用于向父级组件暴露自定义方法的 Hook 之一，它可以让我们定义一个自定义的方法，并将其绑定到 ref 上。useImperativeHandle 接受一个 ref 和一个回调函数，返回一个对象，该对象包含要公开给父级组件的自定义方法。使用 useImperativeHandle 可以提高组件间的通信效率。</p>

      
    </div>
    <footer class="article-footer">
      <a data-url="https://hajcker_1.gitee.io/hajcker_1.gitee.io/2023/04/09/%E8%B7%9F%E7%9D%80Chat%E5%AD%A6%E4%B9%A0React%E4%B9%8BHooks/" data-id="clh8tq38s00084gvgcgo28izl" data-title="跟着Chat学习React之学习Hooks" class="article-share-link">分享</a>
      
      
      
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/hajcker_1.gitee.io/tags/React/" rel="tag">React</a></li></ul>

    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/hajcker_1.gitee.io/2023/04/14/Express%E6%90%AD%E5%BB%BA%E5%90%8E%E5%8F%B0%E6%9C%8D%E5%8A%A1/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">前一篇</strong>
      <div class="article-nav-title">
        
          Express搭建后台服务
        
      </div>
    </a>
  
  
    <a href="/hajcker_1.gitee.io/2023/04/07/%E8%B7%9F%E7%9D%80Chat%E5%AD%A6%E4%B9%A0React%E4%B9%8B%E5%88%9B%E5%BB%BA%E5%88%9D%E5%A7%8B%E9%A1%B9%E7%9B%AE/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">后一篇</strong>
      <div class="article-nav-title">跟着Chat学习React之创建初始项目</div>
    </a>
  
</nav>

  
</article>


</section>
        
          <aside id="sidebar">
  
    

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">标签</h3>
    <div class="widget">
      <ul class="tag-list" itemprop="keywords"><li class="tag-list-item"><a class="tag-list-link" href="/hajcker_1.gitee.io/tags/Node/" rel="tag">Node</a></li><li class="tag-list-item"><a class="tag-list-link" href="/hajcker_1.gitee.io/tags/React/" rel="tag">React</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">标签云</h3>
    <div class="widget tagcloud">
      <a href="/hajcker_1.gitee.io/tags/Node/" style="font-size: 10px;">Node</a> <a href="/hajcker_1.gitee.io/tags/React/" style="font-size: 20px;">React</a>
    </div>
  </div>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">归档</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/hajcker_1.gitee.io/archives/2023/04/">四月 2023</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">最新文章</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/hajcker_1.gitee.io/2023/04/14/Express%E6%90%AD%E5%BB%BA%E5%90%8E%E5%8F%B0%E6%9C%8D%E5%8A%A1/">Express搭建后台服务</a>
          </li>
        
          <li>
            <a href="/hajcker_1.gitee.io/2023/04/09/%E8%B7%9F%E7%9D%80Chat%E5%AD%A6%E4%B9%A0React%E4%B9%8BHooks/">跟着Chat学习React之学习Hooks</a>
          </li>
        
          <li>
            <a href="/hajcker_1.gitee.io/2023/04/07/%E8%B7%9F%E7%9D%80Chat%E5%AD%A6%E4%B9%A0React%E4%B9%8B%E5%88%9B%E5%BB%BA%E5%88%9D%E5%A7%8B%E9%A1%B9%E7%9B%AE/">跟着Chat学习React之创建初始项目</a>
          </li>
        
      </ul>
    </div>
  </div>

  
</aside>
        
      </div>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      
      &copy; 2023 添柴阿杰<br>
      Powered by <a href="https://hexo.io/" target="_blank">Hexo</a>
    </div>
  </div>
</footer>

    </div>
    <nav id="mobile-nav">
  
    <a href="/hajcker_1.gitee.io/" class="mobile-nav-link">Home</a>
  
    <a href="/hajcker_1.gitee.io/archives" class="mobile-nav-link">Archives</a>
  
</nav>
    


<script src="/hajcker_1.gitee.io/js/jquery-3.4.1.min.js"></script>



  
<script src="/hajcker_1.gitee.io/fancybox/jquery.fancybox.min.js"></script>




<script src="/hajcker_1.gitee.io/js/script.js"></script>





  </div>
</body>
</html>